import {Button, Input, Modal, Upload, Divider, Image, message, Select} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {purchaseList, inStock,getDetail,exportDetails} from './service';
import Access from '@/components/Access/Access';

import CreateForm from "./components/CreateForm";
import "./index.css";

import styles from "@/global.less";
import {DownloadOutlined} from "@ant-design/icons";
import {saveFileAs} from "@/utils/utils";
import {storeBaseList} from "@/pages/OrderManagement/StoreOrder/service";

const TableList = (props) => {
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [inStockLoading, handleInStockLoading] = useState(false);
  const [purchaseDetails, handlePurchaseDetails] = useState(false);
  const [record, setRecord] = useState({});
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]);
  const [imgDetail, handleImgDetail] = useState(false);
  const [img, handleImg] = useState([]);
  const [outDetailsModal, handleOutDetailsModal] = useState(false);
  const [storeArray, setStoreArray] = useState([]);
  useEffect(() => {
    getStore();
  }, []);
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  let cancleRowKeys = [];
  const onSelect = (record, selected) => {
    if (!selected) {
      cancleRowKeys = [record.id];
    }
  };
  const onMulSelect = (selected, selectedRows, changeRows) => {
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.id);
    }
  };
  const onChange = (selectedRowKeys, selectedRows) => {

    if (cancleRowKeys.length) {
      const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
      handleMySelectedRowKeys(keys);
      cancleRowKeys = [];
    } else {
      handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
    }

  };
  const simpleColumns = [
    {
      title: '品名',
      dataIndex: 'searchValue',
      hideInTable:true
    },
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
    {
      title: '退货店铺',
      dataIndex: 'storeName',
      hideInSearch: true,
    },
    {
      title: '所属区域',
      dataIndex: 'regionName',
    },
    {
      title: '处理方式',
      dataIndex: 'lossType',
      valueEnum: {
        0: {
          text: '退回工厂',
          status: 'Error',
        },
        1: {
          text: '自行处理',
          status: 'Success',
        },

      },
    },
    {
      title: '类型',
      dataIndex: 'bizType',
      valueEnum: {
        1: {
          text: '化肥',
          status: 'Error',
        },
        2: {
          text: '商超',
          status: 'Success',
        },

      },
    },
    {
      title: '退货时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '退货人',
      dataIndex: 'operator',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '审批中',
          status: 'Error',
        },
        2: {
          text: '已通过',
          status: 'Success',
        },
        9: {
          text: '已完成',
          status: 'Success',
        },
        99: {
          text: '已驳回',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@reportLoss_imgs"}>
                <Button
                  type="primary"
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    getDetail(item.id).then(res=>{
                      handleImg(res.data.imgs);
                      handleImgDetail(true);
                    })
                  }}
                >
                  查看凭据
                </Button>
              </Access>
              {
                (item.lossType === 0 && item.status === 2) ? (
                  <Access accessKey={"@reportLoss_inStock"}>
                    <Button
                      danger
                      type="primary"
                      onClick={() => {
                        setRecord(item);
                        handlePurchaseDetails(true);

                      }}
                    >
                      退货入库
                    </Button>
                  </Access>
                ):null
              }
            </div>
          </>
        );
      },
    },
  ];

  const orderDetailColumns = [
    {
      title: '产品',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
    },

    {
      title: '退货数量',
      dataIndex: 'value',
      hideInSearch: true,
    },
    {
      title: '入库数量',
      dataIndex: 'inStock',
      hideInSearch: true,
    },
    {
      title: '门店库存',
      dataIndex: 'sysStock',
      hideInSearch: true,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      hideInSearch: true,
    },
    {
      title: '规格',
      dataIndex: 'spec',
      hideInSearch: true,
    },
    {
      title: '原因',
      dataIndex: 'reason',
      hideInSearch: true,
    },
  ];

  const detailColumns = [
    {
      title: '商品',
      dataIndex: 'title',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '条码',
      dataIndex: 'barCode',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '规格',
      dataIndex: 'spec',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '退回数量',
      dataIndex: 'value',
      hideInSearch: true,
      width: 10,
    },
    {
      title: '入库数量',
      hideInSearch:true,
      dataIndex: 'inStock',
      width: 10,
      render: (dom, record) => {
        let flag = false;
        let curStock = record.value - (record.inStock?record.inStock:0);
        return <Input
          disabled={curStock <= 0}
          placeholder={curStock}
          onChange={(e) => {
            let inpStock = e.target.value;
            if (inpStock > curStock) {
              message.warn("入库数量已超过未入库数量!");
            }
            record.tempStock = e.target.value;
            flag = true;
          }
          }
          onPressEnter={()=>{
            if (record.tempStock && flag) {
              flag = false;
              showConfirm(record);
            }
          }
          }
          onBlur={()=>{
            if(record.tempStock && flag){
              flag = false;
              showConfirm(record,this)
            }
          }
          }
        />;
      },
    },
  ];

  const outDetailsColumns = [

    {
      title: '退货时间',
      dataIndex: 'purchaseDate',
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '退货时间为必选项',
          },
        ],
      },
    },
    {
      title: '店铺',
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择店铺"
            showSearch
            filterOption={(input, option) => {
              if (option.options) {
                option.options.map((data => {
                  return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }));
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              } else {
                return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }
            }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
                return (
                  <Select.OptGroup label={item_.posName}>
                    {
                      item_.stores.map((item_s, index_s) => {
                        return (
                          <Select.Option value={item_s.id} key={item_s.id}>
                            {item_s.name}
                          </Select.Option>
                        );
                      })
                    }
                  </Select.OptGroup>
                );
              })}
          </Select>
        );
      },
    },
  ];

  const showConfirm = (record)=>{
    Modal.success({
      title: '注意',
      okText:'确定',
      content: '确认要修改'+record.title+'的入库数量为'+record.tempStock+'吗?',
      onOk() {

      },
    });
  };
  const detailRender = (e)=>{

    return <>
      <ProTable
        rowKey={r=>r.id}
        scroll={{x: 1400}}
        bordered
        dataSource={e.details}
        search={false}
        toolBarRender={false}
        pagination={false}
        columns={orderDetailColumns}
      />
    </>
  };
  return (
    <PageContainer>
      <ProTable
        headerTitle="退货列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => purchaseList({...params, sorter, filter})}
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        toolBarRender={() => [
          <Access accessKey={"@report_loss_export"}>
            <Button
              key="report_loss_export"
              type="primary"
              onClick={() => {
                handleOutDetailsModal(true);
              }}
            >
              <DownloadOutlined/> 导出退货列表
            </Button>
          </Access>,
        ]}
        columns={simpleColumns}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        expandedRowRender={detailRender}
        defaultExpandAllRows
      />
      <CreateForm
        width={1300}
        onCancel={() => handlePurchaseDetails(false)}
        modalVisible={purchaseDetails}
        btn_view={(
          <div className={styles.footer_btn}>
            <Button loading={inStockLoading} type="primary" onClick={() => {
              let details = record.details;
              let inStockDetails = [];
              details.filter(data=>mySelectedRowKeys.includes(data.id)).forEach(detail=>{
                inStockDetails.push({
                  detailId:detail.id,
                  outStock:detail.tempStock ? detail.tempStock : (detail.value - (detail.inStock?detail.inStock:0))
                })
              });
              if (inStockDetails.length === 0){
                message.error("请选择要重新入库的明细!");
                return;
              }
              handleInStockLoading(true);
              let params = Object.assign( {details: inStockDetails, id: record.id});
              console.log(params)
              inStock(params).then(res => {
                handleInStockLoading(false);
                if (res?.code === 0) {
                  message.success("入库成功!");
                  handlePurchaseDetails(false);
                  actionRef.current.reload();
                }
              })
            }}>
              提交
            </Button>
          </div>
        )}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">入库明细</Divider>
          <ProTable
            rowKey={r => r.id}
            scroll={{x: 540}}
            bordered
            dataSource={record.details}
            search={false}
            toolBarRender={false}
            pagination={false}
            columns={detailColumns}
            rowSelection={{
              fixed: true,
              selectedRowKeys: mySelectedRowKeys,
              onSelect, //用户手动选择/取消选择某行的回调
              onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
              onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
              onChange, //选中项发生变化时的回调
              getCheckboxProps: record => {
                return {
                  disabled: false
                };
              },
            }}
            tableAlertRender={false}
            tableAlertOptionRender={false}
            footer={() => {
              return (
                <div key="settleFooter" style={{ color: 'red' }}>
                  <div>* 【重新入库】重新进入仓库库存</div>
                </div>
              );
            }}
          />
        </div>
      </CreateForm>
      <CreateForm
        width={800}
        onCancel={() => handleImgDetail(false)}
        modalVisible={imgDetail}
        btn_view={false}
      >
        <div style={{width: '100%', height: '100%'}}>
          <Divider orientation="left">附件</Divider>
          <Image.PreviewGroup>
            {
              img?.map(img => {
                return <Image key={img.id} width={100} height={100} src={img.img}/>
              })
            }
          </Image.PreviewGroup>
        </div>
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        btn_view={null}
        onCancel={() => {
          handleOutDetailsModal(false);
        }}
        modalVisible={outDetailsModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutDetailsModal(false);
            exportDetails(value).then(res=>{
              if (res){
                saveFileAs(res, '退货记录');
              }
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outDetailsColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
